import { deepCopy, getToken } from '@/libs/util';
import ajax from '@/libs/ajax';

export default {
    props: {
        modalWidth: {
            type: Number
        },
        modalOutHeight: {
            type: Number
        },
        // 列表表单Id
        formId: {
            type: Number
        }
    },
    data() {
        return {
            // 原始表单信息
            formData: {
                fields: []
            },
            cloneFormData: {
                fields: []
            },
            filterFields: [],
            columnFields: [],
            createVisible: false, // 是否显示新建窗口
            modalDraggable: true, // 窗口是否可以拖动
            modalHeight: { height: '500px' }, // 窗口样式
            modalLoading: true,
            barcode: "",
            modalTitle: '新建' // 窗口title
        }
    },
    computed: {

    },
    methods: {
        getFormData(callback) {
            // 获取表单数据
            this.getForm({ form_id: this.formId }).then(data => {
                const formInfo = deepCopy(data);
                formInfo.fields = formInfo.fields.map(field => {
                    if (Array.isArray(field.props)) {
                        field.props = {};
                    }

                    if (!field.style) {
                        field.style = { single: 1 }
                    }

                    if (!field.ext) {
                        field.ext = {}
                    }
                    if (field.ext) {
                        const keys = Object.keys(field.ext);
                        if (!keys.includes('sortable')) {
                            field.ext.sortable = true;
                        }
                        if (!keys.includes('resizable')) {
                            field.ext.resizable = true;
                        }
                        if (!keys.includes('editable')) {
                            field.ext.editable = false;
                        }
                        if (!keys.includes('display_format')) {
                            field.ext.display_format = 'yyyy-MM-dd hh:mm:ss';
                        }
                    } else {
                        field.ext = {
                            sortable: true,
                            resizable: true,
                            editable: false,
                            display_format: 'yyyy-MM-dd hh:mm:ss'
                        };
                    }

                    if (field.field_type === "uploadImageOne") {
                        field.props.action = "http://hls.b9bb.cn/api/banner/upload";
                        field.props.headers = {
                            "Authorization": getToken(),
                            'Accept': 'application/vnd.hualaishi.v1+json'
                        };
                        field.props.name = 'img_url'
                        field.props.onSuccess = function (res, file) {
                            file.url = res.data.full_path
                            file.name = res.data.save_path.split('/').pop()
                            return res.data.full_path
                        }
                    }

                    if (field.field_type === "uploadFileOne") {
                        const self = this;
                        if (field.field_name === 'barcode') {
                            const $f = this.$refs.forms.fApi;
                            field.props.beforeUpload = function (file) {
                                self.barcode = file;
                                $f.changeField('barcode', 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar');
                                return false;
                            }
                        }
                    }

                    if (field.field_type === "number") {
                        field.props.default_value = 1;
                    }
                    return field;
                });

                this.formData = { ...formInfo };
                this.filterFields = this.formData.fields.filter(f => f.searchable == 1);
                this.columnFields = this.formData.fields.filter(f => f.show_column == 1);

                callback && callback();
                // this.handleBusinessField(this.formId, formInfo);
            });
        },
        handleOpenCreate() {
            this.createVisible = true;
            const cloneFormData = deepCopy(this.formData);
            cloneFormData.fields = cloneFormData.fields.filter(f => f.display == 1);
            this.cloneFormData = cloneFormData;

            this.selectRow = {};
            this.modalTitle = `新建${this.formData.title}`;
        },
        handleOpenUpdate() {
            const selectRows = this.$refs.tables.getSelection();
            if (selectRows.length === 0 || selectRows.length > 1) {
                this.$Message.error('请选择一行数据');
                return;
            }

            const fields = deepCopy(this.formData).fields.map(field => {
                let defaultValue = selectRows[0][field.field_name];

                if (field.field_type === "number" && defaultValue >= 0) {
                    defaultValue = Number(defaultValue);
                }
                if (field.field_type === "dateTime" && defaultValue >= 0) {
                    if (defaultValue == 0) {
                        defaultValue = "";
                    } else {
                        defaultValue = new Date(Number(defaultValue) * 1000);
                    }
                }
                field.props.default_value = defaultValue;

                if (field.ext && field.ext.editReadonly == 1) {
                    field.props.disabled = true;
                }
                return field;
            });
            this.selectRow = selectRows[0];
            this.cloneFormData.fields = fields;
            this.modalTitle = `编辑${this.formData.title}`;
            this.createVisible = true;
        },
        // 构建树形菜单
        makeSelectTreeData(treeArray, parentId = 0, treeLabelName) {
            return treeArray
                .filter(t => t.parent_id === parentId)
                .map(tree => {
                    return {
                        id: tree.id,
                        label: tree[treeLabelName],
                        children: this.makeSelectTreeData(treeArray, tree.id, treeLabelName)
                    };
                });
        },
        // 删除记录
        handleDelete() {
            const selectRows = this.$refs.tables.getSelection();
            if (selectRows.length === 0) {
                this.$Message.error('请选择数据');
                return;
            }
            if (this.formId !== 9 && selectRows.length > 1) {
                this.$Message.error('请选择一行数据');
                return;
            }

            this.$Modal.confirm({
                title: "提示",
                content: "确认删除？",
                onOk: () => {
                    if (this.formId === 9) {
                        this.deletesFormData({
                            form_id: this.formId,
                            ids: selectRows.map(s => s.id)
                        }).then(res => {
                            this.$Message.success('删除成功');
                            this.$refs.tables.selectAll(false);
                            this.formSaveAfter();
                        });
                    } else {
                        this.deleteFormData({
                            form_id: this.formId,
                            id: selectRows[0].id
                        }).then(res => {
                            this.$Message.success('删除成功');
                            this.$refs.tables.selectAll(false);
                            this.formSaveAfter();
                        });
                    }

                }
            })


        },
        resetModal() {
            this.modalLoading = false;
            this.$nextTick(() => {
                this.modalLoading = true;
            });
        },
        // 新增或编辑表单
        onFormSave() {
            const $f = this.$refs.forms.fApi;

            $f.validate((pass) => {
                $f.submit(formData => {
                    if (Object.keys(formData).includes('barcode')) {
                        delete formData.barcode;
                        let method = "post";
                        let url = "/goods/store";
                        if (this.selectRow.id) {
                            method = "put";
                            url = `/goods/update/${this.selectRow.id}`
                        }

                        ajax({
                            headers: {
                                "Authorization": getToken(),
                                'Accept': 'application/vnd.hualaishi.v1+json'
                            },
                            file: this.barcode,
                            data: formData,
                            method: method,
                            filename: 'barcode',
                            action: url,
                            onProgress: e => {
                                // this.handleProgress(e, file);
                            },
                            onSuccess: res => {
                                this.formSaveAfter();
                            },
                            onError: (err, response) => {
                                this.resetModal();
                            }
                        });
                        return
                    }

                    if (!this.selectRow.id) {
                        this.createFormData({ form_id: this.formId, data: formData }).then(res => {
                            this.$Message.success('添加成功')
                            this.formSaveAfter();
                        }).catch(() => {
                            this.resetModal();
                        });
                    } else {
                        formData.id = this.selectRow.id;
                        this.updateFormData({ form_id: this.formId, data: formData }).then(res => {
                            this.$Message.success('更新成功')
                            this.formSaveAfter();
                        }).catch(() => {
                            this.resetModal();
                        });
                    }
                });
            }, () => {
                this.resetModal();
            });
        },
        updateData(formData) {
            this.updateFormData({ form_id: this.formId, data: formData }).then(res => {
                this.refreshDate();
            }).catch(() => {
                // this.resetModal();
            });
        },
        formSaveAfter() {
            this.modalLoading = false;
            this.$nextTick(() => {
                this.modalLoading = true;
                this.createVisible = false;
                this.refreshDate();
            });
        },
        // 取消编辑或新增
        onFormCancel() {
            this.$refs.forms.fApi.resetFields();
        }
    }
};